package cn.pconline.autoclub.web.app;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.IntfService;
import cn.pconline.autoclub.service.UserForumService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.RegionUtil;
import cn.pconline.autoclub.util.StringUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.app.AppControllerStatic;
import cn.pconline.autoclub.web.UserAuth;

import com.alibaba.fastjson.JSONObject;

/**
 * @author zhouruxuan
 * @date 2015年5月12日 下午12:16:18
 */
@Controller
@RequestMapping(value = "/appapi")
public class AppUserController {

	@Autowired
    private UserAuth userAuth;
	@Autowired
    private UserService userService;
	@Autowired
	private SystemConfig systemConfig;
	@Autowired
	private IntfService intfService;
	
	@Autowired
        private UserForumService userForumService;
        
	private static final int LENGTH_255 = 255;
	
	
	/**
	 * 更新用户资料
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
    @RequestMapping(value = "/1.0/user/updateUserInfo.do", method = RequestMethod.POST)
    public void updateUserInfo(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding4App(request, response);
        //获取参数
        String callback = AppControllerStatic.paramCallback(request);
        String nickName = WebUtils.param(request, "nickName", "");
        int gender = WebUtils.paramInt(request, "gender", 0);
        String birthday = WebUtils.param(request, "birthday", "");
        long cityId = AppControllerStatic.paramCityId(request);
        String cityName = WebUtils.paramTrim(request, "cityName", "");
        long provinceId = AppControllerStatic.paramProvinceId(request);
        String provinceName = WebUtils.paramTrim(request, "provinceName", "");
        String brandId = WebUtils.paramTrim(request, "brandId", "");
        String brandName = WebUtils.paramTrim(request, "brandName", "");
        String serialId = WebUtils.paramTrim(request, "serialId", "");
        String serialName = WebUtils.paramTrim(request, "serialName", "");

        JSONObject jsonObject = new JSONObject();

        //判断用户是否登录
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() <= 0) {
            AppControllerStatic.printLoginErrorMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        if(gender != User.CLUB_MALE && gender != User.CLUB_FEMALE) {
        	AppControllerStatic.printErrorMsg(response, "性别值有误", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
        	return;
        }
        if(StringUtil.length(nickName)>16 || !nickName.matches("([a-zA-Z0-9_]|[^\\x00-\\xff])*")){
        	AppControllerStatic.printErrorMsg(response, "昵称由1-16个字符(字母、数字或下划线)或1-8个中文组成", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
        	return;
        }
        
        //判断是否为直辖市
        boolean flag = isMunicipality(provinceId);
        if(flag) {
        	cityId = provinceId;
        	cityName = provinceName;
        }
        
        //设置carInfo内容
        String carInfo = "";
        if (!brandId.isEmpty() && !brandId.equals("0") && !brandName.isEmpty()) {
            carInfo += brandId + ";" + brandName + ";";
        }
        if (!serialId.isEmpty() && !serialId.equals("0") && !serialName.isEmpty()) {
            carInfo += serialId + ";" + serialName + ";";
        }
        if (carInfo.endsWith(";")) {
            carInfo = carInfo.substring(0, carInfo.length() - 1);
        }
        if (carInfo.length() > LENGTH_255) {
            AppControllerStatic.printErrorMsg(response, "车型信息不正确", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        //更新车友会信息
        user.setNickname(nickName);
        user.setGender(gender);
        Date birthdayDate = WebUtils.parseDate(request, "birthday", null);
        user.setBirthday(birthdayDate);
        user.setCityId(cityId);
        user.setCity(cityName);
        user.setProvinceId(provinceId);
        user.setProvince(provinceName);
        user.setCarInfo(carInfo);
        int result = userService.updateUser(user, "nickname,gender,birthday,city_id,city,province_id,province,car_info");
        
        if(result > 0) {
        	//初始化车友圈
            userForumService.createIfNothing(user.getUid(), cityId, provinceId, carInfo);

            //同步个人资料到个人中心
            String commonSessionId = cn.pconline.passport2.util.WebUtils.getCookie(request, systemConfig.getUserSessionName());
            intfService.updateUserCenter(commonSessionId, null, nickName, gender, null, null, null, cityId, birthday);

            AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        AppControllerStatic.printErrorMsg(response, "更新失败", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
        
    }
	
	/**
     * 判断是否直辖市，特别行政区
     *
     * @param provinceId
     * @return
     */
    public boolean isMunicipality(long provinceId) {
        boolean flag = RegionUtil.specialProIds.contains(provinceId);
        return flag;
    }
	
	/**
	 * 获取用户资料
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
    @RequestMapping(value = "/1.0/user/getUserInfo.do", method = RequestMethod.GET)
    public void getUserInfo(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding4App(request, response);
        //获取参数
        String callback = AppControllerStatic.paramCallback(request);
        long userId = AppControllerStatic.paramUserId(request);

        JSONObject jsonObject = new JSONObject();

        User user = userService.findUser(userId);
        
        if(user == null) {
        	AppControllerStatic.printErrorMsg(response, "用户不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
        	return;
        }
        
        jsonObject.put("nickName", user.getNickname());
        jsonObject.put("gender", user.getGender());
        jsonObject.put("birthday", user.getBirthday());
        jsonObject.put("provinceId", user.getProvinceId());
        jsonObject.put("provinceName", user.getProvince());
        jsonObject.put("cityId", user.getCityId());
        jsonObject.put("cityName", user.getCity());
        
        //careInfo保存格式为(品牌ID;品牌名字;车系ID;车系名字)
        String careInfo = user.getCarInfo();
        if(StringUtils.isNotEmpty(careInfo)) {
        	String[] split = careInfo.split(";");
        	int length = split.length;
        	if(length == 2) {
        		jsonObject.put("serialId", split[0]);
        		jsonObject.put("serialName", split[1]);
        	} else if(length == 4) {
        		jsonObject.put("brandId", split[0]);
        		jsonObject.put("brandName", split[1]);
        		jsonObject.put("serialId", split[2]);
        		jsonObject.put("serialName", split[3]);
        	}
        }
        
        
        if(StringUtils.isEmpty(user.getNickname()) || user.getCityId() <= 0) {
        	jsonObject.put("isComplete", 0);//资料不完整
        } else {
        	jsonObject.put("isComplete", 1);//资料完整
        }

        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
    }
	
	
	/**
	 * 判断用户资料是否完整
	 * 昵称+地区都不为空=完整资料
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
    @RequestMapping(value = "/1.0/user/isCompleteUserInfo.do", method = RequestMethod.GET)
    public void isCompleteUserInfo(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding4App(request, response);
        //获取参数
        String callback = AppControllerStatic.paramCallback(request);
        long userId = AppControllerStatic.paramUserId(request);

        JSONObject jsonObject = new JSONObject();

        User user = userService.findUser(userId);
        
        if(user == null) {
        	AppControllerStatic.printErrorMsg(response, "用户不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
        	return;
        }
        
        String nickName = user.getNickname();
        long cityId = user.getCityId();
        
        if(StringUtils.isEmpty(nickName) || cityId <= 0) {
        	jsonObject.put("isComplete", 0);//资料不完整
        } else {
        	jsonObject.put("isComplete", 1);//资料完整
        }
        
        jsonObject.put("cityId", user.getCityId());
        jsonObject.put("cityName", user.getCity());
        jsonObject.put("provinceId", user.getProvinceId());
        jsonObject.put("provinceName", user.getProvince());

        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
    }
}
